package rolelogic

import (
	"context"

	"go-zero-admin/apps/system/cmd/rpc/internal/svc"
	"go-zero-admin/apps/system/cmd/rpc/syspb"

	"github.com/duke-git/lancet/v2/convertor"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetRoleIdsByUidLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetRoleIdsByUidLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetRoleIdsByUidLogic {
	return &GetRoleIdsByUidLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetRoleIdsByUidLogic) GetRoleIdsByUid(in *syspb.GetRoleIdsByUidReq) (*syspb.GetRoleIdsByUidResp, error) {
	if in.GetUserId() == 0 {
		return &syspb.GetRoleIdsByUidResp{RoleIds: nil}, nil
	}

	// 查询关联角色规则
	enforcer := l.svcCtx.AdapterCasbin.SetCtxSession(l.ctx, nil).Enforcer
	groupPolicy := enforcer.GetFilteredGroupingPolicy(0, convertor.ToString(in.GetUserId()))

	var roleIds []int64
	for _, v := range groupPolicy {
		val, _ := convertor.ToInt(v[1])
		roleIds = append(roleIds, val)
	}

	return &syspb.GetRoleIdsByUidResp{RoleIds: roleIds}, nil
}
